#!/bin/bash
usage()
{
cat << EOF
$0 <snp_file> <seconds> <new_file>

$0 reads the given snp_file and augments every time signature in it to start at NOW + seconds and outputs the result to new_file
EOF
}

SCRIPTNAME=vbs_snpmorphtime
scriptPath=${0%$SCRIPTNAME}
if [ -z "$scriptPath" ]
then
  #invoked from PATH
  scriptPath=$(which $0)
  scriptPath=${scriptPath%$SCRIPTNAME}
fi
source ${scriptPath}vbs_common_functions

FILE=$1
if [ ! -f "$FILE" ]
then
  echo "File $FILE does not exists"
  usage
  exit 1
fi
OFFSET=$2
if ! [[ "$OFFSET" =~ ^[0-9]+$ ]] ; 
then
  usage
   exec >&2; echo "error: Second parameter not a number"; exit 1
fi
OUTFILE=$3
if [ -z $OUTFILE ]
then
  echo "No outputfile specified"
  usage
  exit 1 
fi
if [ -f $OUTFILE ]
then
  echo "File $OUTFILE already exists"
  read -p "Are you sure you want to overwrite it? " -n 1
  printf "\n"
  if [[ ! $REPLY =~ ^[Yy]$ ]]
  then
    usage
    exit 1
  fi
  rm $OUTFILE
fi

RIGHTWHEN=$(date -u +%s)
RIGHTWHEN=$(($RIGHTWHEN+$OFFSET))

while read line
do
  if [[ $line == \!* ]]
  then
    IFS='.' read -a array <<< "$line"
    YEAR=${array[0]:1}
    DAY=${array[1]#0}
    TIME=${array[2]}
    if [ -z "$RECSTART" ]
    then
      RECSTART=$(date -u -d "01/01/${YEAR} + $((${DAY}-1)) days ${TIME}" +%s )
      USETHISDATE=$RIGHTWHEN
    else
      USETHISDATE=$(date -u -d "01/01/${YEAR} + $((${DAY}-1)) days ${TIME}" +%s )
      USETHISDATE=$(($RIGHTWHEN + ($USETHISDATE-$RECSTART)))
    fi
    echo "!$(date -u -d @$USETHISDATE +%Y.%j.%T)" >> $OUTFILE
  else
    echo $line >> $OUTFILE
  fi
done < $FILE
